package cn.edu.bupt.blog.web.admin;

import cn.edu.bupt.blog.po.Tag;
import cn.edu.bupt.blog.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

@Controller
@RequestMapping("/admin")
public class TagsController {
    
    @Autowired
    private TagService tagService;

    @GetMapping("/tags")
    public String tags(@PageableDefault(size = 3,sort = {"id"},direction = Sort.Direction.DESC) Pageable pageable,
                       Model model) {
        // 将查询获得的数据保存到model，返回到前端
        model.addAttribute("page",tagService.listTag(pageable));
        return "/admin/tags";
    }

    @GetMapping("/tags/input")
    public String tagsInput(Model model) {
        model.addAttribute("tag",new Tag());
        return "/admin/tags-input";
    }
    
    @PostMapping("/tags")
    public String save(@Valid Tag tag, BindingResult result, RedirectAttributes attributes){
        if(result.hasErrors()){
            return "/admin/tags-input";
        }
        Tag t = tagService.saveTag(tag);
        if(t == null) {
            // 添加失败
            attributes.addFlashAttribute("message","添加标签失败！");
        }else{
            // 添加成功
            attributes.addFlashAttribute("message","添加标签成功！");
        }
        return "redirect:/admin/tags";
    }

    @GetMapping("/tags/editInput")
    public String editInput(@RequestParam Long id, Model model) {
        // 根据id查询分类对象，并保存到model，返回给前端
        model.addAttribute("tag",tagService.getTag(id));
        return "/admin/tags-input";
    }

    @PostMapping("/tags/editPost")
    public String editPost(@Valid Tag Tag, BindingResult result, RedirectAttributes attributes,@RequestParam Long id){
        if(result.hasErrors()){
            return "/admin/tags-input";
        }
        Tag t = tagService.updateTag(id,Tag);
        if(t == null) {
            // 添加失败
            attributes.addFlashAttribute("message","更新分类失败！");
        }else{
            // 添加成功
            attributes.addFlashAttribute("message","更新分类成功！");
        }
        return "redirect:/admin/tags";
    }

    @GetMapping("/tags/delete")
    public String delete (@RequestParam Long id,RedirectAttributes attributes) {
        tagService.deleteTag(id);
        attributes.addFlashAttribute("message","删除成功！");
        return "redirect:/admin/tags";
    }
}
